package com.tsugun.mediaplayer.view.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.model.entity.MusicModel;
import com.tsugun.mediaplayer.model.entity.SheetModel;
import com.tsugun.mediaplayer.presenter.provider.ListProvider;
import com.tsugun.mediaplayer.presenter.utils.ConverterHelper;
import com.tsugun.mediaplayer.presenter.utils.SettingPreferenceHelper;
import com.tsugun.mediaplayer.view.activity.IndexActivity;
import com.tsugun.mediaplayer.view.adapter.MusicItemAdapter;
import com.tsugun.mediaplayer.view.adapter.MusicMenuAdapter;
import com.tsugun.mediaplayer.view.adapter.SheetItemMenuAdapter;
import com.tsugun.mediaplayer.view.widget.MusicMenuDialog;
import com.tsugun.mediaplayer.view.widget.SlidingRelativeLayout;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 下载管理界面
 * Created by shize on 2017/4/20.
 */

public class FolderFragment extends BaseFragment implements MusicMenuAdapter.OnMenuItemClickListener {

    public static final String INTENT_STRING_FOLDER_TITLE = "com.TsuGun.MediaPlayer.intent.folderTitle";

    @BindView(R.id.id_sliding_body)
    SlidingRelativeLayout mSlidingLayout;
    @BindView(R.id.id_folder_bg)
    RelativeLayout mRlBg;
    @BindView(R.id.id_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.id_recycler)
    RecyclerView mRvFolderMusic;

    private View mFragment;
    private Context mContext;
    private Unbinder unbinder;
    private IndexActivity indexActivity;
    private ListProvider mProvider;

    private List<MusicModel> mData;
    private MusicItemAdapter mMusicItemAdapter;
    private String mFolderName;

    private int mPosition; // 当前点击菜单的位置
    private List<String> mMenuList; // 菜单列表项目
    private MusicMenuAdapter mMenuAdapter; // 菜单适配器
    private MusicMenuDialog mDialog; // 菜单会话框
    private String mTitle; // 歌曲标题
    private List<SheetModel> mSheets; // 歌单列表

    private SheetItemMenuAdapter mSheetAdapter;
    private MusicMenuDialog mSheetDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mFragment = inflater.inflate(R.layout.fragment_folder, container, false);
        mContext = container.getContext();
        unbinder = ButterKnife.bind(this, mFragment);

        initData();
        bindData();
        return mFragment;
    }

    @Override
    protected void setSettingTheme() {
        int themeColor = indexActivity.getThemeColor();
        mToolbar.setBackgroundColor(themeColor);
        mRlBg.setBackgroundColor(SettingPreferenceHelper.INSTANCE.getBACKGROUND_COLOR());
    }

    private void initData() {
        mFolderName = getArguments().getString(INTENT_STRING_FOLDER_TITLE);
        indexActivity = (IndexActivity) mContext;
        mProvider = indexActivity.getListProvider();
        mData = (List<MusicModel>) mProvider.getMusicByFolder(mFolderName);
        initLocalMusicMenu();
    }

    /**
     * 初始化本地歌曲菜单dialog数据
     */
    private void initLocalMusicMenu() {
        // 当前点击位置
        mPosition = 0;
        // 菜单项目标题
        mMenuList = new ArrayList<>();
        Collections.addAll(mMenuList, getResources().getStringArray(R.array.menu_item_title_list));
        // 图标
        int[] mIcons = new int[]{R.drawable.ic_menu_item_next, R.drawable.ic_menu_item_collection,
                R.drawable.ic_menu_item_artist, R.drawable.ic_menu_item_album,
                R.drawable.ic_menu_item_details, R.drawable.ic_menu_item_delete};
        mMenuAdapter = new MusicMenuAdapter(mContext, mMenuList, mIcons);
        mMenuAdapter.setOnMenuClickListener(this);
    }

    @Override
    public void onMenuClick(int pos) {
        // 菜单项点击事件
        switch (pos) {
            case MENU_ITEM_NEXT_PLAY:
                indexActivity.setNextPlayMusic(mData.get(mPosition).getId());
                break;
            case MENU_ITEM_COLLECTION:
                showSheetList();
                break;
            case MENU_ITEM_ARTIST:
                startArtistFragment(mData.get(mPosition).getArtist(), indexActivity);
                break;
            case MENU_ITEM_ALBUM:
                startAlbumFragment(mData.get(mPosition).getAlbum(), indexActivity);
                break;
            case MENU_ITEM_INFO:
                showMusicInfoDialog(mData.get(mPosition), mContext);
                break;
            case MENU_ITEM_DELETE:
                showDeleteAlertDialog(mContext);
                break;
        }
        mDialog.dismiss();
    }

    /**
     * 添加音乐到歌单
     */
    private void addMusicToSheet(int position) {
        SheetModel oldSheet = mSheets.get(position);
        List<String> strId = oldSheet.getMusicIdList();
        String sheetId = mData.get(mPosition).getId();
        if (strId.contains(sheetId)) {
            Snackbar.make(mRvFolderMusic, R.string.str_duplicate_music, Snackbar.LENGTH_LONG).show();
            return;
        }
        strId.add(sheetId);
        mProvider.editSheetAddMusic(oldSheet, strId);
        mSheets.remove(oldSheet);
        oldSheet.setMusicIdList(strId);
        mSheets.add(oldSheet);
        // 更新歌单列表
        indexActivity.updateSheetList();
        Snackbar.make(mRvFolderMusic, R.string.str_add_complete, Snackbar.LENGTH_LONG).show();
    }

    /**
     * 显示歌单会话框
     */
    private void showSheetList() {
        mTitle = getString(R.string.str_music)+mData.get(mPosition).getTitle();
        mSheets = new ArrayList<>();
        mSheets.addAll((Collection<? extends SheetModel>) mProvider.getSheet());
        mSheetAdapter = new SheetItemMenuAdapter(mContext, mSheets);
        mSheetAdapter.setProvider(mProvider);
        mSheetAdapter.setOnSheetItemClickListener(new SheetItemMenuAdapter.OnSheetItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mSheetDialog.dismiss();
                addMusicToSheet(position);
            }
        });
        MusicMenuDialog.Builder builder = new MusicMenuDialog.Builder(mContext, mSheetAdapter, mTitle);
        mSheetDialog = builder.create();
        mSheetDialog.show();
    }

    @Override
    protected void deleteMusic() {
        mData.remove(mPosition);
        mMusicItemAdapter.notifyDataSetChanged();
    }

    private void bindData() {
        bindSliding();
        bindToolbar();
        bindList();
    }

    /**
     * 绑定列表
     */
    private void bindList() {
        mMusicItemAdapter = new MusicItemAdapter(mContext, mData);
        mMusicItemAdapter.setOnMusicItemClickListener(new MusicItemAdapter.OnMusicItemClickListener() {
            @Override
            public void onItemClick(int position) {
                indexActivity.playMusicById(mData.get(position).getId());
            }

            @Override
            public void onMenuClick(int position) {
                mPosition = position;
                showMenu(mData);
            }
        });
        mRvFolderMusic.setAdapter(mMusicItemAdapter);
        mRvFolderMusic.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL, false));
        setSettingTheme(mRvFolderMusic);
        indexActivity.setAdapter(mMusicItemAdapter);
    }

    /**
     * 绑定标题栏
     */
    private void bindToolbar() {
        mToolbar.setTitle(ConverterHelper.INSTANCE.getFolderName(mFolderName));
        mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back, null));
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                indexActivity.getMusicFragmentManager().backFragment();
            }
        });
    }

    /**
     * 绑定滑动
     */
    private void bindSliding() {
        mSlidingLayout.setOnSlidingListener(new SlidingRelativeLayout.OnSlidingListener() {
            @Override
            public void onDown() {

            }

            @Override
            public void onAnimationEnd(boolean isClose) {
                if (isClose) {
                    indexActivity.getMusicFragmentManager().backFragment();
                }
            }
        });
    }

    /**
     * 显示歌曲菜单
     */
    private void showMenu(List<MusicModel> mResult) {
        String title = getString(R.string.str_music) + mResult.get(mPosition).getTitle();
        // 初始化菜单项目歌手和专辑显示
        mMenuList.remove(MENU_ITEM_ARTIST);
        mMenuList.add(MENU_ITEM_ARTIST, getString(R.string.str_menu_item_artist)
                + mResult.get(mPosition).getArtist());
        mMenuList.remove(MENU_ITEM_ALBUM);
        mMenuList.add(MENU_ITEM_ALBUM, getString(R.string.str_menu_item_album)
                + mResult.get(mPosition).getAlbum());
        MusicMenuDialog.Builder builder = new MusicMenuDialog.Builder(mContext, mMenuAdapter
                , title);
        mDialog = builder.create();
        mDialog.show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
